package com.feng.fengmall.cart.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 过滤器
 * 只有登录了才可以打开购物车
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    //使用ThreadLocal ？？
    public static ThreadLocal<MemberRespVo> loginUser=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (attribute!=null){
            loginUser.set(attribute);
            return true;
        }else {
//            request.setAttribute("msg","请先登录");
            response.sendRedirect("http://localhost:20000/login.html");
            return false;
        }
    }

//    /**
//     * 重写peiHandle
//     * 目标方法执行之前
//     * @param request
//     * @param response
//     * @param handler
//     * @return  true表示拦截当前请求，false表示不拦截当前请求 ??????
//     * @throws Exception
//     */
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        HttpSession session = request.getSession();
//        MemberRespVo attribute = (MemberRespVo) session.getAttribute(AuthConstant.LOGIN_USER);
//        if (attribute==null){
//            response.sendRedirect("http://localhost:20000/login.html");
//        }
//        return true;
//    }
}
